package com.xiumu.common.log4j2;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.pattern.ConverterKeys;
import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
import org.apache.logging.log4j.core.pattern.PatternConverter;

/**
 * 重写Log4j2日志格式化, 简化全类名输出
 * 只输出包名首字母和类名
 */
@Plugin(name = "FirstLetterPackageNameConverter", category = PatternConverter.CATEGORY)
@ConverterKeys({"flc"})
public class FirstLetterPackageNameConverter extends LogEventPatternConverter {

    protected FirstLetterPackageNameConverter(String name, String style) {
        super(name, style);
    }

    /**
     * 获取实例
     * @param config
     * @param options
     * @return
     */
    public static FirstLetterPackageNameConverter newInstance(final Configuration config, final String[] options) {
        return new FirstLetterPackageNameConverter("fpn", null);
    }

    @Override
    public void format(LogEvent event, StringBuilder toAppendTo) {
        String[] parts = event.getLoggerName().split("\\.");
        for (int i = 0; i < parts.length; i++) {
            if (i < parts.length - 2) {
                toAppendTo.append(parts[i].charAt(0)).append(".");
            }else {
                toAppendTo.append(parts[i]).append(".");
            }
        }
    }
}
